package org.dxy.domain.handler.route;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.port.CommandHandler;
import org.dxy.domain.port.repository.IRouteRepository;
import org.dxy.domain.command.route.BatchDeleteRouteCommand;
import org.dxy.domain.command.route.DeleteRouteCommand;
import org.dxy.domain.event.DomainEvent;
import org.dxy.domain.model.aggregate.Route;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 批量删除工艺路线命令处理器
 * @author: dxy
 * @createTime: 2025/8/17 11:49
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class BatchDeleteRouteCommandHandler implements CommandHandler<BatchDeleteRouteCommand, Void> {

    private final IRouteRepository routeRepository;

    @Transactional
    @Override
    public CommandResult<Void> handle(BatchDeleteRouteCommand command) {
        try {
            List<Long> routeIds = command.routeIds();
            if (routeIds == null || routeIds.isEmpty()) {
                return CommandResult.fail("删除的工艺路线ID列表不能为空");
            }

            log.info("开始处理批量删除工艺路线命令: routeIds={}", routeIds);

            List<String> failedRoutes = new ArrayList<>();
            List<DomainEvent> allEvents = new ArrayList<>();
            int successCount = 0;

            // 逐个处理删除
            for (Long routeId : routeIds) {
                try {
                    // 1. 检查工艺路线是否存在
                    Route route = routeRepository.findById(routeId);
                    if (route == null) {
                        failedRoutes.add("工艺路线ID " + routeId + " 不存在");
                        continue;
                    }

                    // 2. 执行删除业务逻辑
                    route.delete(new DeleteRouteCommand(routeId));

                    // 3. 保存聚合根
                    routeRepository.save(route);

                    // 4. 收集领域事件
                    allEvents.addAll(route.getDomainEvents());
                    
                    successCount++;
                    
                } catch (IllegalStateException e) {
                    failedRoutes.add("工艺路线ID " + routeId + ": " + e.getMessage());
                } catch (Exception e) {
                    log.error("删除工艺路线失败: routeId={}", routeId, e);
                    failedRoutes.add("工艺路线ID " + routeId + ": " + e.getMessage());
                }
            }

            // 5. 发布所有领域事件
            for (DomainEvent event : allEvents) {
                log.debug("发布领域事件: {}", event);
            }

            // 6. 构建结果消息
            StringBuilder resultMsg = new StringBuilder();
            resultMsg.append("批量删除完成，成功删除 ").append(successCount).append(" 条记录");
            
            if (!failedRoutes.isEmpty()) {
                resultMsg.append("，失败 ").append(failedRoutes.size()).append(" 条：")
                        .append(String.join("; ", failedRoutes));
                
                // 如果有失败的，但也有成功的，返回部分成功
                if (successCount > 0) {
                    log.warn("批量删除工艺路线部分成功: 成功{}条，失败{}条", successCount, failedRoutes.size());
                    return CommandResult.success(null, resultMsg.toString());
                } else {
                    // 全部失败
                    log.error("批量删除工艺路线全部失败: {}", failedRoutes);
                    return CommandResult.fail(resultMsg.toString());
                }
            }

            log.info("批量删除工艺路线命令处理完成: 成功删除{}条记录", successCount);
            return CommandResult.success(null, resultMsg.toString());

        } catch (Exception e) {
            log.error("批量删除工艺路线失败: routeIds={}", command.routeIds(), e);
            return CommandResult.fail("批量删除工艺路线失败: " + e.getMessage());
        }
    }
}